package com.linkgie.galaxyframework.httpproxy;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.linkgie.galaxyframework.utils.CollectionUtils;

/**
 * HTTP 参数表；
 * 
 * @author huanghaiquan
 *
 */
public class HttpParams implements HttpParameters {

	private Map<String, List<ParamEntry>> params = new LinkedHashMap<>();

	public ParamEntry[] getAll() {
		List<ParamEntry> allParams = new ArrayList<>();
		for (List<ParamEntry> namedParams : params.values()) {
			allParams.addAll(namedParams);
		}
		return allParams.toArray(new ParamEntry[allParams.size()]);
	}

	@Override
	public Set<String> getNames() {
		return params.keySet();
	}

	@Override
	public String getValue(String name) {
		List<ParamEntry> entries = params.get(name);
		if (entries == null || entries.isEmpty()) {
			return null;
		}
		return entries.get(0).getValue();
	}

	@Override
	public String[] getValues(String name) {
		List<ParamEntry> entries = params.get(name);
		if (entries == null || entries.isEmpty()) {
			return null;
		}
		return CollectionUtils.toArray(entries, String.class, ParamEntry::getValue);
	}

	public ParamEntry set(String name, String value) {
		List<ParamEntry> values = params.get(name);
		if (values == null) {
			values = new ArrayList<>();
			params.put(name, values);
		}
		ParamEntry p = new ParamEntry(name, value);
		values.add(p);
		return p;
	}

	public boolean isEmpty() {
		return params.isEmpty();
	}

	/**
	 * 合并；
	 * 
	 * @param extParams
	 * @param prefix    附加的新参数的前缀；
	 */
	public void merge(HttpParams extParams) {
		merge(extParams, null);
	}

	/**
	 * 合并；
	 * 
	 * @param extParams
	 * @param prefix    附加的新参数的前缀；
	 */
	public void merge(HttpParams extParams, String prefix) {
		if (prefix == null || prefix.length() == 0) {
			ParamEntry[] paramArr = extParams.getAll();
			for (ParamEntry np : paramArr) {
				set(np.getName(), np.getValue());
			}
		} else {
			ParamEntry[] paramArr = extParams.getAll();
			for (ParamEntry np : paramArr) {
				set(prefix + np.getName(), np.getValue());
			}
		}
	}
}
